import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:youfangtong_module/net/interceptor.dart';

class DioUtils {

  // 创建一个DioUtils类的静态变量_instance，并初始化为null
  static DioUtils? _instance;

  Dio? _dio;

  /// 私有构造函数，防止外部直接new实例
  DioUtils._internal() {
    var options = BaseOptions(
      connectTimeout: const Duration(seconds: 30), // 连接超时时间
      receiveTimeout: const Duration(seconds: 30), // 响应数据超时时间
      responseType: ResponseType.plain, // 返回字符串
      validateStatus: (status) { // 不使用HTTP状态码判断，
        return true;
      },
      baseUrl: getApiBaseUrl() // 基础Url
    );
    _dio = Dio(options);

    // 统一添加身份验证请求头
    _dio?.interceptors.add(AuthInterceptor());

    // 打印Log
    _dio?.interceptors.add(LoggingInterceptor());
  }

  /// 提供公共静态的方法获取实例
  static DioUtils? getInstance() {
    _instance ??= DioUtils._internal();
    return _instance;
  }

  /// BaseUrl
  String getApiBaseUrl() {
    return "https://testyfxcx.ehousechina.com/";
  }

  asyncRequestNetwork<T>(
      BuildContext context,
      Method method,
      String url,
      {
        required Function(T t) onSuccess
      }) {
    // Stream.fromFuture()
  }

  _requestDioData(String url, Method m,
      {dynamic data,
        required Map<String, dynamic> queryParameters,
        CancelToken? cancelToken,
        Options? options}) async {
    String? method = _getRequestMethod(m);
    var response = await _dio?.request(
        url,
        data: data, // 请求体数据
        queryParameters: queryParameters, // URL查询参数
        cancelToken: cancelToken, // 可选，用于取消请求
        options: _checkOptions(m,options)
    );


  }

  String _getRequestMethod(Method method) {
    String? m;
    switch(method) {
      case Method.post:
        m = 'POST';
        break;
      case Method.get:
        m = "GET";
        break;
      case Method.put:
        m = "GET";
        break;
      case Method.patch:
        m = "GET";
        break;
      case Method.delete:
        m = "GET";
        break;
      case Method.head:
        m = "GET";
        break;
    }

    return m;
  }

  Options _checkOptions(method,options) {
    options ??= Options();
    options.method = method;
    return options;
  }

}

enum Method {get,post,put,patch,delete,head}